import json
from time import sleep
from threading import Thread
import cv2
from PIL import Image

from util import changeSizeImages
from variable import Variable
from game import Game
from multiprocessing import Process, freeze_support
import psutil
import sys
import io
import os

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", line_buffering=True)

# 获取py 文件所在目录
current_path = os.path.dirname(os.path.realpath(sys.argv[0]))

# 把这个目录设置成工作目录
os.chdir(current_path)


def run_proc():
    try:
        if not Variable.handle:
            print("找不到模拟器")
            return
        if not -2 < Image.open("./images/id.png").width - 58 / 2 * Variable.scale < 2:
            print("开始压缩图片")
            changeSizeImages()
            print("压缩图片结束")
        print("开始运行")
        Game().start()
    except cv2.error:
        print("\n请勿最小化模拟器")
    except Exception as e:
        print(e)


def status(pause):
    while True:
        tmp = input("")
        if tmp == "p":
            print("脚本暂停")
            pause.suspend()  # 暂停子进程
        if tmp == "g":
            print("脚本继续")
            pause.resume()
        if tmp == "s":
            pause.kill()
            return


if __name__ == "__main__":
    run_proc()
    # freeze_support()
    # if len(sys.argv) > 1:
    #     try:
    #         Variable.init(json.loads(sys.argv[1]))
    #     except json.decoder.JSONDecodeError as f:
    #         print("参数格式化错误")
    # p = Process(target=run_proc)
    # p.start()
    # pid = p.pid  # 获取子进程的pid
    # pause = psutil.Process(pid)  # 传入子进程的pid
    # sleep(1)
    # Thread(target=status, args=(pause,), daemon=True).start()
    # while True:
    #     if not psutil.pid_exists(pid):
    #         print("运行完成")
    #         sys.exit(0)
